/*
 * @Descripttion: 
 * @version: 
 * @Author: sueRimn
 * @Date: 2021-09-03 23:30:27
 * @LastEditors: sueRimn
 * @LastEditTime: 2021-09-06 21:09:19
 */

'use strict';
const Service = require('egg').Service;
/**
 * 一对一队列演示
 */

// 频道名称
const queueName = 'hasone'

/**
 * @service MqService MQ
 */
class MqService extends Service {

    /**
   * @summary 生成者
   * @description 根据Id获取图书信息
   * @router get /mq/send
   * @request query  msg msg
   * @response 200
   */
  async send() {
    // 1. 获取要发送的消息
    const { msg } = this.ctx.query
    // 2. 创建频道
    const ch = await this.app.amqplib.createChannel();
    // 3. 创建队列 durable 关闭持久化存储
    await ch.assertQueue(queueName, { durable: false }  );
    // 4. 发送消息
    const ok = await ch.sendToQueue(queueName, Buffer.from(msg));
    // 5. 关闭连接
    await ch.close();
    this.ctx.apiSuccess(msg)
  }


   /**
   * @summary 消费者
   * @description 根据Id获取图书信息
   * @router get /mq/work
   * @request query  msg msg
   * @response 200
   */
  async work() {
    // 1. 创建频道
    const ch = await this.app.amqplib.createChannel();
    // 2. 选择队列
    await ch.assertQueue(queueName, { durable: false });
    //3. 接收队列的消息
    const resultMsg = await new Promise(resolve => ch.consume(queueName, msg => resolve(msg), { noAck: true }));

    // 4. 显示消息内容
    if (resultMsg !== null) {
      ch.ack(resultMsg);
      await ch.close();

      const { content } = resultMsg;
      console.log('队列消费成功')
      this.ctx.apiSuccess(content.toString())
    } else {
    this.apiSuccess(content.toString(),'队列消费失败',500)
    //   this.ctx.body = '队列消费失败'
    //   this.ctx.status = 500;
    }
  }
}

module.exports = MqService;
